package chapter20CyclicBarrier;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 当线程达到一定条件时，执行某一项任务
 * Created by LinGer on 2019/7/1
 */
public class CyclicBarrierTest2 extends Thread {

    private static int SIZE = 5;
    private static CyclicBarrier cb;

    @Override
    public void run() {
        System.out.println(this.getName() + " wait for CyclicBarrier.");

        try {
            cb.await();

            //cb的参与者数量等于5时，才能继续往后执行
            System.out.println(this.getName() + " continued.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        cb = new CyclicBarrier(SIZE, new Runnable() {
            @Override
            public void run() {
                System.out.println("CyclicBarrier's parties is: " + cb.getParties());
            }
        });

        for (int i = 0; i < SIZE; i++) {
            new CyclicBarrierTest2().start();
        }
    }
}
